using CommonInitializer;
using IdentityService.Domain;
using IdentityService.Domain.InterfaceAntiCorruptionLayer;
using IdentityService.Infrastructure;
using IdentityService.Infrastructure.Options;
using IdentityService.Infrastructure.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = WebApplication.CreateBuilder(args);

#region 通用配置
//builder.ConfigureDbConfiguration();
builder.ConfigureExtraServices(new InitializerOptions
{
    EventBusQueueName = "IdentityService.WebAPI",
    LogFilePath = "c:/temp/IdentityService.log"
});
#endregion

#region 配置信息
// 添加配置绑定
// 从配置文件读取配置信息
//var configuration = new ConfigurationBuilder()
//    .SetBasePath(Directory.GetCurrentDirectory())
//    .AddJsonFile("appsettings.json")
//    .Build();
//builder.Services.Configure<SendCloudSmsSettings>(configuration.GetSection("SendCloudSmsSettings"));
// 从数据库的T_Config中读取配置信息
builder.Services.Configure<SendCloudSmsSettings>(builder.Configuration.GetSection("SendCloudSmsSettings"));
#endregion

//builder.Services.AddControllers();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new() { Title = "IdentityService.WebAPI", Version = "v1" });
    //c.AddAuthenticationHeader();
});

#region Identity鉴权框架的相关的配置
// 密码加密
builder.Services.AddDataProtection();

// 身份验证
/*
 * 登录、注册的项目除了要启用WebApplicationBuilderExtensions中的初始化之外，还要如下的初始化
 * 不要用AddIdentity，而是用AddIdentityCore
 * 因为用AddIdentity会导致JWT机制不起作用，AddJwtBearer中回调不会被执行，因此总是Authentication校验失败
 */
//https://github.com/aspnet/Identity/issues/1376
// 声明了一个 IdentityBuilder 对象 idBuilder，通过 builder.Services.AddIdentityCore<User>() 方法来创建
IdentityBuilder idBuilder = builder.Services.AddIdentityCore<User>(options =>
{
    options.Password.RequireDigit = false;     // 禁用了必须包含数字的密码规则
    options.Password.RequireLowercase = false;     // 禁用了必须包含小写字母的密码规则
    options.Password.RequireNonAlphanumeric = false;     // 禁用了必须包含非字母数字字符的密码规则
    options.Password.RequireUppercase = false;     // 禁用了必须包含大写字母的密码规则
    options.Password.RequiredLength = 6;     // 设置密码的最小长度为 6
    // options.User.RequireUniqueEmail = true;     // 不能设定 RequireUniqueEmail，否则不允许邮箱为空
    // 以下两行，把 GenerateEmailConfirmationTokenAsync 验证码缩短
    options.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultEmailProvider;
    options.Tokens.EmailConfirmationTokenProvider = TokenOptions.DefaultEmailProvider;
});
idBuilder = new IdentityBuilder(idBuilder.UserType, typeof(Role), builder.Services);
// 将数据库连接、用户、角色与IdentityBuilder绑定
idBuilder.AddEntityFrameworkStores<IdDbContext>().AddDefaultTokenProviders()
    //.AddRoleValidator<RoleValidator<Role>>()
    .AddRoleManager<RoleManager<Role>>()
    .AddUserManager<IdUserManager>();
#endregion


#region 注册服务
if (builder.Environment.IsDevelopment())
{
    builder.Services.AddScoped<IEmailSender, MockEmailSender>();
    builder.Services.AddScoped<ISmsSender, MockSmsSender>();
    //builder.Services.AddScoped<IEmailSender, SendCloudEmailSender>();
    //builder.Services.AddScoped<ISmsSender, SendCloudSmsSender>();
}
else
{
    builder.Services.AddScoped<IEmailSender, SendCloudEmailSender>();
    builder.Services.AddScoped<ISmsSender, SendCloudSmsSender>();
}
#endregion

var app = builder.Build();

// Configure the HTTP request pipeline.
if (builder.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "IdentityService.WebAPI v1"));
}
app.UseApexDefault();
app.MapControllers();
app.Run();